package yweb

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"strings"
	"yweb/context"
)

//返回的jsonBean
type BaseJsonBean struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

//创建jsonBean
func NewBaseJsonBean(code int, message string, data interface{}) *BaseJsonBean {
	return &BaseJsonBean{
		Code:    code,
		Message: message,
		Data:    data,
	}
}

//文件过滤器
func StaticServerBegin(ctx *context.Context) {

	wd, err := os.Getwd()
	if err != nil {
		log.Println("获取系统路径失败：", err)
	}

	path := ctx.Request.URL.Path
	//判断是否有.
	if strings.Contains(path, ".") {
		request_type := path[strings.LastIndex(path, "."):]
		switch request_type {
		case ".css":
			ctx.ResponseWriter.Header().Set("content-type", "text/css; charset=utf-8")
			wd = wd + "/static/"
		case ".js":
			ctx.ResponseWriter.Header().Set("content-type", "text/javascript; charset=utf-8")
			wd = wd + "/static/"
		default:
		}
	}

	fin, err := os.Open(wd + path)
	if err != nil {

		log.Println("读取文件失败：", err)
		//关闭文件句柄
		fin.Close()

		//返回json头
		ctx.ResponseWriter.Header().Set("content-type", "text/json; charset=utf-8")

		result := NewBaseJsonBean(404, "", "")
		bytes, _ := json.Marshal(result)
		ctx.ResponseWriter.Write([]byte(string(bytes)))

		log.Println("返回数据：", string(bytes))

		return
	}

	fd, _ := ioutil.ReadAll(fin)
	ctx.ResponseWriter.Write([]byte(fd))

}
